package com.superkripts.sktools.function;

import ch.njol.skript.Skript;
import ch.njol.skript.util.Date;
import com.superkripts.sktools.annotation.Param;
import com.superkripts.sktools.value.Now;
import me.clip.placeholderapi.PlaceholderAPI;
import com.superkripts.sktools.annotation.SkriptFunction;
import com.superkripts.sktools.value.Console;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;

import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;

/**
 * 通用的一些函数
 */
public class GenericFunctions {

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 执行命令
     *
     * @param cmd    命令
     * @param sender 命令发送者
     */
    @SkriptFunction(value = "cmd", since = "1.0.0", description = "执行命令")
    public static void dispatchCommand(String cmd, @Param(defaultType = Console.class) CommandSender sender) {
        Bukkit.dispatchCommand(sender, cmd);
    }

    /**
     * 为玩家解析占位符
     *
     * @param player 玩家
     * @param text   文本
     * @return 新的文本
     */
    @SkriptFunction(value = "papi", since = "1.0.0", description = "解析PlaceholderAPI占位符", requiredPlugin = "PlaceholderAPI")
    public static String parsePlaceholder(@Param(nullable = true) OfflinePlayer player, String text) {
        return PlaceholderAPI.setBracketPlaceholders(player, text);
    }

    /**
     * 日期格式化
     *
     * @param date   日期
     * @param format 格式
     * @return 日期文本
     */
    @SkriptFunction(value = "dateFormat", since = "1.0.0", description = "时间格式化")
    public static String dateFormat(@Param(defaultType = Now.class) Date date, @Param(defaultValue = "yyyy-MM-dd HH:mm:ss") String format) {
        if (format.equals("yyyy-MM-dd HH:mm:ss")) {
            return dateFormat.format(date.getTimestamp());
        }
        return new SimpleDateFormat(format).format(date.getTimestamp());
    }

    /**
     * 数字格式化
     *
     * @param number       数字
     * @param format       格式
     * @param roundingMode 取整模式
     * @return 数字文本
     */
    @SkriptFunction(value = "numberFormat", since = "1.0.0", description = "数字格式化")
    public static String numberFormat(Number number, @Param(defaultValue = ",###.##") String format, @Param(defaultValue = "HALF_EVEN") String roundingMode) {
        DecimalFormat decimalFormat = new DecimalFormat(format);
        if (!"HALF_EVEN".equalsIgnoreCase(roundingMode)) {
            try {
                decimalFormat.setRoundingMode(RoundingMode.valueOf(roundingMode.toUpperCase()));
            } catch (IllegalArgumentException e) {
                Skript.error("Error executing function 'numberFormat()', Invalid rounding mode: " + roundingMode);
                Skript.error("Rounding mode optional values: " + Arrays.toString(RoundingMode.values()));
            }
        }
        return decimalFormat.format(number);
    }
}
